import { AvatarUploadResult } from '../types/user';
import { http } from "../utils/http"
import { baseURL } from '../utils/config'

/**
 * 通用文件上传方法
 */
export const uploadFile = (file: any) => {
	return new Promise<AvatarUploadResult>((resolve, reject) => {
		uni.uploadFile({
			url: baseURL + '/admin/sys-file/upload',
			filePath: file.tempFilePath || file.path,
			name: 'file',
			header: {
				'Authorization': getBasicAuth('')
			},
			success: (res) => {
				try {
					const data = JSON.parse(res.data);
					if (res.statusCode >= 200 && res.statusCode < 300) {
						resolve(data.data);
					} else {
						uni.showToast({
							icon: 'none',
							title: data.msg || '上传失败'
						});
						reject(data);
					}
				} catch (error) {
					uni.showToast({
						icon: 'none',
						title: '上传响应解析失败'
					});
					reject(error);
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: 'none',
					title: '上传失败，请重试'
				});
				reject(err);
			}
		});
	});
}

/**
 * 上传头像
 */
export const uploadUserAvatar = (file : any) => {
	return uploadFile(file);
}

// 从utils/http.ts复制getBasicAuth函数以避免循环依赖
import { userInfo } from '@/stores/user'
function getBasicAuth(basicAuth : string) {
	// 获取用户信息
	//1.如果没有登录，那么basicAuth开头是Basic
	if (!userInfo.value?.basicAuth) {
		const model = 'custom:custom'
		// 使用兼容小程序的方式替代TextEncoder
		// 创建一个长度为model.length的Uint8Array
		const uint8Array = new Uint8Array(model.length);
		// 手动编码字符串
		for (let i = 0; i < model.length; i++) {
			uint8Array[i] = model.charCodeAt(i);
		}
		const arrayBuffer = uint8Array.buffer as ArrayBuffer
		return 'Basic ' + uni.arrayBufferToBase64(arrayBuffer)
	} else {
		//2.如果已经登录，那么basicAuth开头是Bearer
		return `${userInfo.value?.basicAuth}`

	}
}